<template>
  <div class="store-selector">
    <div class="current-store-info" v-if="currentStore">
      <el-avatar
        v-if="currentStore.logo"
        :src="getLogoUrl(currentStore.logo)"
        :size="28"
        class="store-logo"
      />
      <span class="store-name">{{ currentStore.name }}</span>
      <el-tag
        v-if="currentStore.status === 'open'"
        size="small"
        type="success"
        effect="light"
        class="store-status"
      >
        营业中
      </el-tag>
      <el-tag
        v-else-if="currentStore.status === 'closed'"
        size="small"
        type="info"
        effect="light"
        class="store-status"
      >
        已关闭
      </el-tag>
      <el-tag
        v-else-if="currentStore.status === 'pending'"
        size="small"
        type="warning"
        effect="light"
        class="store-status"
      >
        审核中
      </el-tag>
      <el-tag
        v-else-if="currentStore.status === 'rejected'"
        size="small"
        type="danger"
        effect="light"
        class="store-status"
      >
        未通过
      </el-tag>
    </div>
    <el-dropdown
      trigger="click"
      class="store-switch-dropdown"
      :disabled="stores.length <= 1"
    >
      <el-button size="small" class="switch-btn">
        切换店铺
        <el-icon style="margin-left: 4px"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="store in stores"
            :key="store.id"
            :disabled="store.id === currentStoreId"
            @click="handleStoreChange(store.id)"
          >
            <div class="dropdown-store-option">
              <el-avatar
                v-if="store.logo"
                :src="getLogoUrl(store.logo)"
                :size="20"
                class="store-logo"
              />
              <span class="store-name">{{ store.name }}</span>
              <el-tag
                v-if="store.status === 'open'"
                size="small"
                type="success"
                effect="light"
                class="store-status"
              >
                营业中
              </el-tag>
              <el-tag
                v-else-if="store.status === 'closed'"
                size="small"
                type="info"
                effect="light"
                class="store-status"
              >
                已关闭
              </el-tag>
              <el-tag
                v-else-if="store.status === 'pending'"
                size="small"
                type="warning"
                effect="light"
                class="store-status"
              >
                审核中
              </el-tag>
              <el-tag
                v-else-if="store.status === 'rejected'"
                size="small"
                type="danger"
                effect="light"
                class="store-status"
              >
                未通过
              </el-tag>
            </div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted, watch, defineComponent } from "vue";
import { useRouter } from "vue-router";
import { useMerchantStore } from "@/store";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "StoreSelector",
  components: {
    ArrowDown,
  },
  setup() {
    // logo url 兼容
    const getLogoUrl = (logo: string) => {
      if (!logo || logo === "string") return undefined;
      if (/^https?:\/\//.test(logo)) return logo;
      return (
        (import.meta.env.VITE_API_BASE_URL || window.location.origin) + logo
      );
    };
    const router = useRouter();
    const merchantStore = useMerchantStore();

    const currentStoreId = computed({
      get: () => merchantStore.currentStoreId,
      set: (val) => merchantStore.setCurrentStore(val),
    });

    const stores = computed(() => merchantStore.stores);
    const loading = computed(() => merchantStore.loading);

    const currentStore = computed(() =>
      stores.value.find((s) => s.id === currentStoreId.value)
    );

    // 切换店铺
    const handleStoreChange = (storeId: string) => {
      if (storeId !== currentStoreId.value) {
        merchantStore.setCurrentStore(storeId);
        ElMessage.success(
          `已切换到店铺: ${
            merchantStore.stores.find((s) => s.id === storeId)?.name || ""
          }`
        );
      }
    };

    // 组件挂载时获取店铺列表
    onMounted(() => {
      const initializeStores = async () => {
        try {
          if (stores.value.length === 0) {
            await merchantStore.fetchStores();
          }
        } catch (error) {
          console.error('StoreSelector 初始化失败:', error);
        }
      };
      
      initializeStores();
    });

    return {
      currentStoreId,
      stores,
      loading,
      currentStore,
      handleStoreChange,
      getLogoUrl,
    };
  },
});
</script>

<style scoped>
.store-selector {
  display: flex;
  align-items: center;
  gap: 18px;
  min-height: 32px;
}
.current-store-info {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 180px;
  max-width: 320px;
  font-size: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.store-logo {
  flex-shrink: 0;
}
.store-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
}
.store-status {
  flex-shrink: 0;
  margin-left: 4px;
}
.switch-btn {
  min-width: 90px;
  height: 32px;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.store-switch-dropdown {
  margin-left: 8px;
}
.dropdown-store-option {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 120px;
  font-size: 14px;
}
</style>
